//跟进计划列表
var $invoiceTable = $('#invoiceForm');
var abs = new verjs_select();
//防止表头与表格不对齐
$(window).resize(function () {
    $invoiceTable.bootstrapTable('resetView');
});

$(function () {

    //高级筛选日期--配置参数
    $('.date-input').datepicker({
        language: "zh-CN",
        autoClose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    //开票列表
    followPlanFormList();
    //初始化公司下拉框(--搜索条件)
    loadCompanySelect();

})

function followPlanFormList() {
//先销毁表格
    $invoiceTable.bootstrapTable('destroy');
    $invoiceTable.bootstrapTable({
        classes: 'table table-hover table-bordered',
        url: '/orderInvoice/selectOrderInvoiceList',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'invoiceTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'chsCustomerOrderInvoiceId',
        idField: 'chsCustomerOrderInvoiceId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'chsCustomerOrderInvoiceId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat},
            {title: '订单编号',field: 'orderNumber', align: 'left', valign: 'middle'},
            {title: '所属客户', field: 'customerName', align: 'left', valign: 'middle'},
            {title: '所属人', field: 'createPeopleName', align: 'left', valign: 'middle'},
            {title: '发票金额', field: 'invoiceMoney', align: 'right', valign: 'middle'},
            {title: '开票日期', field: 'invoiceTm', align: 'left', valign: 'middle'},
            {title: '发票类型', field: 'invoiceType', align: 'left', valign: 'middle',
                formatter: function(value,index,row){
                    var html="";
                    if (value == 1){
                        html = "纸质发票";
                    }
                    if (value == 2){
                        html = "电子发票";
                    }
                    return html;
                }
            },
            {title: '发票状态', field: 'invoiceStatus', align: 'left', valign: 'middle',
                formatter: function(value,index,row){
                    var html="";
                    if (value == 0){
                        html = "已申请";
                    }
                    if (value == 1){
                        html = "已开具";
                    }
                    if (value == 2){
                        html = "部分开具";
                    }
                    return html;
                }
            },
            {title: '审批状态', field: 'examineStatus', align: 'left', valign: 'middle',
                formatter: function(value,index,row){
                    var html="";
                    if (value == 0){
                        html = "<img src='../../../images/no-icon.png' style='margin-right: 10px'><span>未审批</span>";
                    }
                    if (value == 1){
                        html = "<img src='../../../images/yes-icon.png' style='margin-right: 10px'><span>审批通过</span>";
                    }
                    if (value == 2){
                        html = "<img src='../../../images/mdiImg/no-force-icon.png' style='margin-right: 10px'><span>退回</span>";
                    }
                    return html;
                }
            },
            {title: '操作',field: 'operate',align: 'left',formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#orderTableList').css({
                minWidth: $('#orderTableList').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0,11,],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}


function searchOrderList(type) {
    $('.all').addClass('active-second');
    $('.today').removeClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $('.year').removeClass('active-second');
    $("#dateType").val("all");
    if (type === 1) {//普通条件查询
        $invoiceTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams2});
        // 点击搜索重置表单并收起高级搜索 需传入高级搜索id #filterContent
        $('#filterContent').collapse('hide').on('hidden.bs.collapse', function () {
            resetOrderQueryParams('#filterContent');
        });
    } else if (type == 2) {//高级搜索条件查询
        $('#orderNumberMin').val('');
        $invoiceTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
    }
}

function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    params.customerName = $.trim($('#customerName2').val());//客户名称
    params.userName = $.trim($('#userName').val());//原所属人名称
    params.startDate = $.trim($('#startDate').val());//开始计划日期
    params.endDate = $.trim($('#endDate').val());//截止计划日期
    params.invoiceStatus = $.trim($('#invoiceStatus').val());//状态
    params.invoiceType = $.trim($('#invoiceType').val());//发票类型
    params.startMoney = $.trim($('#startMoney').val());//起始开票金额
    params.endMoney = $.trim($('#endMoney').val());//截止开票金额
    params.examineStatus = $.trim($('#examineStatus').val());//审批状态
    params.dateType = $('#dateType').val();
    params.qx = $('#qx').val();
    return params;
}

function queryParams2(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    params.customerName = $.trim($('#customerName').val());//客户名称
    params.dateType = $('#dateType').val();
    params.qx = $('#qx').val();
    return params;
}

//重置高级查询
function clearAllData() {
    window.location.reload();
}

function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 全部/周/月/年切换
 * @param time
 */
function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisYear");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    if (time == 'today') {//今天
        $('.today').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisToday");
    }
    $invoiceTable.bootstrapTable('refreshOptions', {pageNumber: 1});
}

/**
 * 获得客户名称下拉
 */
function getCustomerSelect(){
    var qx = $("#qx").val();
    var url ='/customerController/getCustomerList'
    if (qx == 2){
        url ='/customerController/getCustomerListByComp'
    }
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: url,
        cache : false,
        data:{
        },
        async : false,
        success: (function (data) {
            if (data.code == "000000") {

                // let html = [];
                // $.each(data.data, function (n, value) {
                //     html.push('<option value="' + value.customerId + '">' + value.customerName + '</option>')
                // });
                // $('#customerInput').html(html.join(''));

                var html = '<option value="">请选择</option>';
                $.each(data.data, function(n, value) {
                    // html += "<option value=" + value.customerId + " >" +  value.customerName + "</option>";
                    if(customerIdexistence!='undefined' && customerIdexistence==value.customerId){
                        html += '<option value="'+value.customerId +'" selected>' + value.customerName + '</option>';
                    }else{
                        html += '<option value="'+ value.customerId+'">' + value.customerName + '</option>';
                    }

                });

                $('#customerInput').html(html).selectpicker('refresh');
            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}
//删除计划
function delFollowPlan(cpFollowPlanId) {
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: '/followPlan/deleteFollowPlan',
        cache : false,
        data:{"cpFollowPlanId":cpFollowPlanId
        },
        async : false,
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '提示',
                    content: '取消成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                window.location.reload();
                            }
                        }
                    }
                });
            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

// 获取联系人
function changeName(_this) {
    var $this = _this;
    //联系人姓名
    var name = $.trim($("#name").val());
    //从哪跳转到跟进页面（0：线索；1：客户）
    var source = 1;
    //线索/客户id
    var id = $("#customerInput").val();
    var status;
    if (!name) {
        status = '0';
    } else {
        status = '1';
    }
    $.ajax({
        url: '/clueContact/clueContact/echo',
        data: {
            name: name,
            status: status,
            id: id,
            source: source
        },
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        success: function (data) {
            if (data.code == '000000') {
                $("#nameBox").css("display", 'block');
                $("#nameBox").html('');
                if (data.data.length <= 0) {//把页面上之前赋值的联系人id置空
                } else {
                    let str = '';
                    for (let i = 0; i < data.data.length; i++) {
                        str += '<li><a href="javascript:void(0);" class="name-item" onclick="getTel(\'' + data.data[i].contactName + '\',\'' + data.data[i].contactInformation + '\')">' + data.data[i].contactName + '</a></li>'
                    }
                    $("#nameBox").html(str);
                }
            }
        }
    });

    // 点击输入框和下拉菜单以外范围，关闭提示下拉菜单
    $(document).click(function (e) {
        var con = $($this).parents('.form-content');
        if (!con.is(e.target) && con.has(e.target).length === 0) {
            $("#nameBox").slideUp(160);
        }
    })
}

function getTel(name, phone) {
    $("#name").val(name);
    $("#phone").val(phone);
    $("#nameBox").css("display", 'none');
}

/**
 * 加载公司下拉列表
 */
function loadCompanySelect() {
    $.getJSON("/sysCompany/selectCompanies", function (data) {
        if (data.code == '000000') {
            var optionHtml = '';
            var optionArr = data.data;
            var optionSelected = $('#companySelect option:selected').val();
            //公司搜索条件下拉框
            var searchCompanyOptionHtml = '<option value="">全部</option>';
            optionArr.map(function (item, index) {
                searchCompanyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $('#searchCompanySelect').html(searchCompanyOptionHtml);
            var selectDate = [];
            for (var i = 0, len = data.data.length; i < len; i++) {
                var company = data.data[i];
                var selectCompany = {};
                selectCompany.id = company.companyId;
                selectCompany.name = company.companyName;
                selectDate.push(selectCompany);
            }
            /*abs.render({
                elem: "#search",
                data: selectDate,
                init_value: [1],
                body_height: 300,
                checkbox: true,
                name: "test"
            });*/
            $('#searchoption-list').css('z-index',1000);
            $('#searchCompanySelect').selectpicker({
                sanitize: true,
                size: 8
            });
        }
    });
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    //\''+row.cpFollowPlanId+'\'
    let html = '';
    html += '<button class="btn btn-default" data-toggle="collapse" data-target="#addInputMoney" aria-expanded="false" aria-controls="addInputMoney" ' +
        'onclick="">详情</button>';
    html += '<button class="btn btn-default" data-toggle="collapse" data-target="#addInputMoney" aria-expanded="false" aria-controls="addInputMoney" ' +
        'onclick="delApply(\''+row.chsCustomerOrderInvoiceId+'\')">撤回</button>';
    html += '</ul></div>'
    return html;
}

function delApply(chsCustomerOrderInvoiceId) {
    $.alert({
        title: '提示',
        content: "确定要撤回开票申请吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        url: '/orderInvoice/delOrderInvoice?id='+chsCustomerOrderInvoiceId,
                        type: 'post',
                        dataType: "json",
                        contentType: "application/json;charset=utf-8",
                        success: (function (data) {
                            if(data.code == '000000'){
                                $.alert("操作成功");
                                window.location.reload();
                            } else {
                                $.alert(data.message);
                            }
                        }),
                        error: (function (res) {
                            $.alert("操作失败");
                        })
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    })
}


